package cn.hl.hm.controller;

import cn.hl.hm.dao.DriverMapper;
import cn.hl.hm.dao.RechargeRecoardMapper;
import cn.hl.hm.dao.TRechargeActivityMapper;
import cn.hl.hm.entity.Driver;
import cn.hl.hm.entity.RechargeRecoard;
import cn.hl.hm.entity.RechargeRecoardBean;
import cn.hl.hm.entity.TRechargeActivity;
import cn.hl.hm.service.BackstageOperationRecordService;
import cn.hl.hm.service.DriverService;
import cn.hl.hm.service.RechargeRecoardService;
import cn.hl.hm.util.AppPager;
import cn.hl.hm.util.InfoCode;
import cn.hl.hm.util.OrderUtil;
import cn.hl.hm.util.Result;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.vizhuo.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import smsClient.TestSDKClient;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/backRechargeController")
public class BackRechargeController {
	private static Logger logger = Logger.getLogger(BackRechargeController.class);
	private final static SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
	@Autowired
	RechargeRecoardService rechargeRecoardService;
	@Autowired
	TRechargeActivityMapper tRechargeActivityMapper;
	@Autowired
	DriverMapper driverMapper;

	@Autowired
	DriverService driverService;

	@Autowired
	BackstageOperationRecordService operationRecordService;

	@Autowired
	RechargeRecoardMapper rechargeRecoardMapper;

	@RequestMapping(value = "/selectInfo", method = RequestMethod.POST)
	public String selectDriverRouteList(@RequestParam Integer pageId, RechargeRecoard rechargeRecoard,@RequestParam  Integer pageCount,
										HttpServletRequest request, HttpServletResponse response) throws IOException {


		AppPager handle = AppPager.handle(pageId, pageCount);
		rechargeRecoard.setPageId(handle.getPageId());
		rechargeRecoard.setPageCount(handle.getPageCount());
		request.setCharacterEncoding("UTF-8");
		logger.info("进入后台充值列表方法----selectInfo");
		logger.info("园区收费/资金---充值记录/余额明细列表---backRechargeController/selectInfo");
		try {
			if (StringUtils.isNotBlank(rechargeRecoard.getBeString())
					&& StringUtils.isNotBlank(rechargeRecoard.getEndString())) {
				if (rechargeRecoard.getBeString().trim().equals("''")) {

				} else if (rechargeRecoard.getEndString().trim().equals("''")) {

				} else if (rechargeRecoard.getBeString().trim().equals("\"\"")) {

				} else if (rechargeRecoard.getEndString().trim().equals("\"\"")) {

				} else {
					rechargeRecoard.setBeString(rechargeRecoard.getBeString().trim() + " 00:00:00");
					rechargeRecoard.setEndString(rechargeRecoard.getEndString().trim() + " 23:59:59");
				}

			}
			List<RechargeRecoard> rechargeRecoardList = rechargeRecoardService.selectRechargeRecoardAss(rechargeRecoard);
			if (null != rechargeRecoardList && rechargeRecoardList.size() > 0) {/*
				for (RechargeRecoard rechargeRecoard2 : rechargeRecoardList) {
					if (rechargeRecoard2 != null && rechargeRecoard2.getRechargeActivityId() != null) {
						TRechargeActivity selectByPrimaryKey = tRechargeActivityMapper.selectByPrimaryKey(rechargeRecoard2.getRechargeActivityId());
						rechargeRecoard2.setRechargeActivity(selectByPrimaryKey);
					}
					if (rechargeRecoard2 != null && rechargeRecoard2.getUserphone() != null) {
						Driver driver = new Driver();
						driver.setDriverAccount(rechargeRecoard2.getUserphone());
						List<Driver> selectDriver = driverMapper.selectDriver(driver);
						if (selectDriver != null && selectDriver.size() > 0) {
							rechargeRecoard2.setDriver(selectDriver.get(0));
						}
					}
				}
				rechargeRecoard.setPageCount(null);
				rechargeRecoard.setPageId(null);
				int selectRechargeRecoardCount = rechargeRecoardMapper.selectRechargeRecoardCount(rechargeRecoard);

				Map<String, Object> pageInfo = AppPager.getPageInfo(rechargeRecoardList, pageCount, selectRechargeRecoardCount, pageId);

				Result.ok(pageInfo, InfoCode.SUCCESS, response);
				return null;
			*/
				rechargeRecoard.setPageCount(null);
				rechargeRecoard.setPageId(null);
				int selectRechargeRecoardCount = rechargeRecoardMapper.selectRechargeRecoardCount(rechargeRecoard);

				Map<String, Object> pageInfo = AppPager.getPageInfo(rechargeRecoardList, pageCount, selectRechargeRecoardCount, pageId);

				Result.ok(pageInfo, InfoCode.SUCCESS, response);
				return null;

			} else {
				Result.ok(null, InfoCode.SUCCESS, response);
				return null;

			}
		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
			return null;
		}
	}

	@RequestMapping(value = "/selectInfoByCondition", method = RequestMethod.POST)
	public String selectInfoByCondition(Integer pageId, RechargeRecoard rechargeRecoard, Integer pageCount,
										HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.info("园区收费---司机交易详情---backRechargeController/selectInfoByCondition");
		request.setCharacterEncoding("UTF-8");
		try {
			if (StringUtils.isNotBlank(rechargeRecoard.getBeString())
					&& StringUtils.isNotBlank(rechargeRecoard.getEndString())) {
				if (rechargeRecoard.getBeString().trim().equals("''")) {

				} else if (rechargeRecoard.getEndString().trim().equals("''")) {

				} else if (rechargeRecoard.getBeString().trim().equals("\"\"")) {

				} else if (rechargeRecoard.getEndString().trim().equals("\"\"")) {

				} else {
					rechargeRecoard.setBeString(rechargeRecoard.getBeString().trim() + " 00:00:00");
					rechargeRecoard.setEndString(rechargeRecoard.getEndString().trim() + " 23:59:59");
				}
			}
			Double totalIncome = 0.0;
			Double totalConsume = 0.0;
			rechargeRecoard.setOperType(null);
			rechargeRecoard.setStatus("2");
			//根据司机ID查询充值成功的
			List<RechargeRecoard> rechargeRecoardList = rechargeRecoardService.selectRechargeRecoard(rechargeRecoard);
			for (RechargeRecoard rechargeRecoard2 : rechargeRecoardList) {
				if (rechargeRecoard2.getAmount() != null) {
					if (rechargeRecoard2.getOperType() == 1) {
						totalIncome += Double.parseDouble(rechargeRecoard2.getAmount().toString());
					} else {
						totalConsume += Double.parseDouble(rechargeRecoard2.getAmount().toString());
					}
				}

			}
			RechargeRecoardBean rb = new RechargeRecoardBean();
			rb.setTotalConsume(totalConsume.toString());
			rb.setTotalIncome(totalIncome.toString());
			if (rechargeRecoardList != null && rechargeRecoardList.size() > 0) {
				rb.setRemainCash(rechargeRecoardList.get(0).getRemainCash().toString());
				rb.setRechargeRecoardList(rechargeRecoardList);
			}

			// if (null != rechargeRecoardList&&rechargeRecoardList.size()>0) {
			//
			// for (RechargeRecoard rechargeRecoard2 : rechargeRecoardList) {
			// if(rechargeRecoard2!=null&&rechargeRecoard2.getRechargeActivityId()!=null){
			// TRechargeActivity selectByPrimaryKey =
			// tRechargeActivityMapper.selectByPrimaryKey(rechargeRecoard2.getRechargeActivityId());
			// rechargeRecoard2.setRechargeActivity(selectByPrimaryKey);
			// }
			// if(rechargeRecoard2!=null&&rechargeRecoard2.getUserphone()!=null){
			// Driver driver = new Driver();
			// driver.setDriverAccount(rechargeRecoard2.getUserphone());
			// List<Driver> selectDriver = driverMapper.selectDriver(driver);
			// if(selectDriver!=null&&selectDriver.size()>0){
			// rechargeRecoard2.setDriver(selectDriver.get(0));
			// }
			// }
			// }
			// Result.ok(rechargeRecoardList, InfoCode.SUCCESS, response);
			// return null;
			// } else {
			// Result.ok(null, InfoCode.SUCCESS, response);
			// return null;

			// }
			Result.ok(rb, InfoCode.SUCCESS, response);
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
			return null;
		}
	}

	@RequestMapping(value = "/driverRecharge", method = RequestMethod.POST)
	public @ResponseBody String getRechargeCode(@RequestParam("driverAccount") String driverAccount, // 用户账户
												Integer rechargeId, // 充值金额Id
												@RequestParam("userId") Integer userId,
												@RequestParam("userMail") String userMail,
												BigDecimal userDefinedAmount,//自定义金额

												Integer type, HttpServletRequest request, HttpServletResponse response) {
		logger.info("配载费相关导出---配载费--司机充值---backRechargeController/driverRecharge");

		if(rechargeId!=null) {
			TRechargeActivity tRechargeActivity = tRechargeActivityMapper.selectByPrimaryKey(rechargeId);
			if (tRechargeActivity == null) {
				logger.info("参数有误");
				Result.ok(null, InfoCode.FAILURE, response);
				return null;
			}
		}


		if(userDefinedAmount!=null) {
			if(userDefinedAmount.compareTo(new BigDecimal(0))<=0) {

				logger.info("参数有误");
				Result.ok(null, InfoCode.FAILURE, response);
				return null;

			}
		}

		try {
			Driver param = new Driver();
			param.setDriverAccount(driverAccount);
			List<Driver> selectDriver = driverService.selectDriver(param);
			if (selectDriver != null && selectDriver.size() > 0) {
				Driver driver = selectDriver.get(0);
				if(rechargeId!=null) {
					TRechargeActivity tRechargeActivity = tRechargeActivityMapper.selectByPrimaryKey(rechargeId);
					if (tRechargeActivity.getAmount().toString().equals("0.00") && driver.getGiftFlag().equals("1")) {
						Result.ok(null, InfoCode.DRIVER_GIFT_ERROR, response);
						return null;
					}
				}

				BigDecimal remainCash = driver.getRemainCash();
				if (remainCash == null) {
					remainCash = new BigDecimal(0);
				}
				// 生成充值Code
				String code = OrderUtil.getInstance().getRoadFeeOrderCode();
				RechargeRecoard r = new RechargeRecoard();
				r.setRechargeCode(code);
				r.setCreateTime(new Date());
				r.setStatus("2"); // 充值成功
				r.setType(type); // 线下充值
				r.setUserphone(driver.getDriverAccount());
				if(rechargeId!=null) {
					TRechargeActivity tRechargeActivity = tRechargeActivityMapper.selectByPrimaryKey(rechargeId);
					r.setAmount(tRechargeActivity.getGiftAmount().add(tRechargeActivity.getAmount()));
					r.setRechargeActivityId(rechargeId);
				}else {
					//自定义
					r.setAmount(userDefinedAmount);
				}

				r.setDriverId(driver.getId());

				BigDecimal amount = r.getAmount();
				if (amount == null) {
					amount = new BigDecimal(0);
				}
				r.setRemainCash(remainCash.add(amount));
				r.setOperType(1);// 操作类型

				operationRecordService.insertSelective(userId,
						userMail, "司机充值：【" + code + "】");
				r.setRechargeAdminAccount(userMail);

				int addRechargeRecoard = rechargeRecoardService.addRechargeRecoard(r);
				if (addRechargeRecoard > 0) {

					Driver driver2 = new Driver();
					driver2.setRemainCash(r.getRemainCash());
					driver2.setId(r.getDriverId());
					if(rechargeId!=null) {
						TRechargeActivity tRechargeActivity = tRechargeActivityMapper.selectByPrimaryKey(rechargeId);
						if (tRechargeActivity.getAmount().toString().equals("0.00")) {
							driver2.setGiftFlag("1");
						}
					}

					int res = driverService.updateDriver(driver2);
					if (res > 0) {

						Result.ok(null, InfoCode.SUCCESS, response);
						// 操作记录
						if(rechargeId!=null) {
							TRechargeActivity tRechargeActivity = tRechargeActivityMapper.selectByPrimaryKey(rechargeId);
//							TestSDKClient.testSendSMSE(driverAccount,
//									"【华凌叮当到】温馨提示您，您的账户于" + new Date().toLocaleString() + "分通过线下充值"
//											+ tRechargeActivity.getAmount() + "元，活动奖励" + tRechargeActivity.getGiftAmount()
//											+ "元，账户余额" + driver2.getRemainCash() + "元【华凌叮当到：400-998-3903】");
							SendSmsRequest smsRequest = new SendSmsRequest();
							smsRequest.setTemplateParam("{\"currentDate\":\""+new Date().toLocaleString()+"\",\"rechargeAmount\":\""+tRechargeActivity.getAmount()+ "\",\"giftAmount\":\""+ tRechargeActivity.getGiftAmount()+ "\",\"remainCash\":\""+ driver2.getRemainCash() +"\"}");
							TestSDKClient.sendSmsByAli("SMS_110495051",smsRequest,driver.getDriverAccount(),"华凌叮当到");

						}else {
//							TestSDKClient.testSendSMSE(driverAccount,
//									"【华凌叮当到】温馨提示您，您的账户于" + new Date().toLocaleString() + "分通过线下充值"
//											+ userDefinedAmount + "元，"
//													+ "账户余额" + driver2.getRemainCash() + "元【华凌叮当到：400-998-3903】");
							SendSmsRequest smsRequest = new SendSmsRequest();
							smsRequest.setTemplateParam("{\"currentDate\":\""+new Date().toLocaleString()+"\",\"rechargeAmount\":\""+userDefinedAmount+"\",\"remainCash\":\""+driver2.getRemainCash()+"\"}");
							TestSDKClient.sendSmsByAli("SMS_110585047",smsRequest,driver.getDriverAccount(),"华凌叮当到");
						}

						return null;
					} else {
						Result.ok(null, InfoCode.FAILURE, response);
						return null;
					}
				} else {
					Result.ok(null, InfoCode.PARAM_ERROR, response);
					return null;
				}
			} else {
				Result.ok(null, InfoCode.RESET_ERROR, response);
				return null;
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			Result.ok(null, InfoCode.FAILURE, response);
		}
		return null;
	}

	@RequestMapping(value = "/updateRechargeReceiptsStatus", method = RequestMethod.POST)
	public @ResponseBody String updateRecharge(@RequestParam("id") Integer id, // 用户账户
											   @RequestParam("receiptsStatus") Integer receiptsStatus, // 充值金额Id
											   HttpServletRequest request, HttpServletResponse response) {
		logger.info("配载费相关导出---开发票---backRechargeController/updateRechargeReceiptsStatus");
		try {
			RechargeRecoard rr = new RechargeRecoard();
			rr.setId(id);
			rr.setReceiptsStatus(receiptsStatus + "");

			int update = rechargeRecoardService.updateRechargeRecoard(rr);
			if (update > 0) {
				Result.ok(null, InfoCode.SUCCESS, response);
			} else {
				Result.ok(null, InfoCode.FAILURE, response);
				return null;
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			Result.ok(null, InfoCode.FAILURE, response);
		}
		return null;
	}

	@RequestMapping(value = "/driverCashDetail", method = RequestMethod.POST)
	public String driverCashDetail(RechargeRecoard rechargeRecoard, HttpServletRequest request,
								   HttpServletResponse response) throws IOException {
		logger.info("园区收费---司机账户明细---backRechargeController/driverCashDetail");
		if (StringUtils.isBlank(rechargeRecoard.getBeString()) || rechargeRecoard.getBeString().trim().equals("''")
				|| rechargeRecoard.getBeString().trim().equals("\"\"")) {
			rechargeRecoard.setBeString("2017-03-01");
		}
		if (StringUtils.isBlank(rechargeRecoard.getEndString()) || rechargeRecoard.getEndString().trim().equals("''")
				|| rechargeRecoard.getEndString().trim().equals("\"\"")) {
			rechargeRecoard.setEndString(DateUtil.getCurrentDate());
		}
		rechargeRecoard.setSearchEndTime(rechargeRecoard.getEndString() + " 23:59:59");
//		else{
//			SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
//			String str = rechargeRecoard.getEndString().trim();
//			try {
//				Date dt = shortSdf.parse(str);
//				Calendar rightNow = Calendar.getInstance();
//				rightNow.setTime(dt);
//				rightNow.add(Calendar.DAY_OF_YEAR, 1);// 日期加10天
//				rechargeRecoard.setSearchEndTime(shortSdf.format(rightNow.getTime()) + " 23:59:59");
//			} catch (ParseException e) {
//				e.printStackTrace();
//			}
//		}


		rechargeRecoard.setBeString(rechargeRecoard.getBeString().trim() + " 00:00:00");
		rechargeRecoard.setEndString(rechargeRecoard.getEndString().trim() + " 23:59:59");

//		RechargeRecoard searchBeginAmount = new RechargeRecoard();
//		searchBeginAmount.setSearchTime(rechargeRecoard.getBeString());
//		RechargeRecoard searchEndAmount = new RechargeRecoard();
//		searchEndAmount.setSearchEndTime(rechargeRecoard.getBeString());
		List<RechargeRecoard> rrList = rechargeRecoardService.driverCashDetail(rechargeRecoard);
		// List<RechargeRecoard> rrListReturn = new ArrayList<>();
		// for (RechargeRecoard rr : rrList) {
		// searchBeginAmount.setDriverId(rr.getDriverId());
		// searchEndAmount.setDriverId(rr.getDriverId());
		// searchBeginAmount.setStatus("2");
		// searchEndAmount.setStatus("2");
		// List<RechargeRecoard> rrr =
		// rechargeRecoardService.selectRechargeRecoardByUserPhone(searchBeginAmount);
		// if(rrr!=null && rrr.size()>0){
		// if(rrr.get(0).getRemainCash()!=null){
		// if(rrr.get(0).getOperType()==2){
		// rr.setBeginAmount(rrr.get(0).getRemainCash().toString());
		// }else{
		// rr.setBeginAmount(rrr.get(0).getRemainCash().subtract(rrr.get(0).getAmount()).toString());
		// }
		//
		// }else{
		// rr.setBeginAmount("0");
		// }
		// }else{
		// //如果选择的日期 没有发生交易记录。则获取小于该日期的记录，按照日期倒叙，并取第一条
		// List<RechargeRecoard> rrr2 =
		// rechargeRecoardService.selectRechargeRecoardByUserPhone(searchEndAmount);
		// if(rrr2!=null && rrr2.size()>0){
		// if(rrr2.get(0).getRemainCash()!=null){
		// if(rrr2.get(0).getOperType()==1){
		// rr.setBeginAmount(rrr2.get(0).getRemainCash().subtract(rrr2.get(0).getAmount()).toString());
		// }else{
		// rr.setBeginAmount(rrr2.get(0).getRemainCash().toString());
		// }
		//
		// }else{
		// rr.setBeginAmount("0");
		// }
		// }
		// }
		// RechargeRecoard searchEndAmount1=new RechargeRecoard();
		// searchEndAmount1.setSearchEndTime(rechargeRecoard.getEndString());
		// searchEndAmount1.setDriverId(rr.getDriverId());
		// searchEndAmount1.setStatus("2");
		// RechargeRecoard searchBeginAmount1=new RechargeRecoard();
		// searchBeginAmount1.setSearchTime(rechargeRecoard.getEndString());
		// searchBeginAmount1.setStatus("2");
		// searchBeginAmount1.setDriverId(rr.getDriverId());
		// List<RechargeRecoard> rrr2 =
		// rechargeRecoardService.selectRechargeRecoardByUserPhone(searchBeginAmount1);
		// if(rrr2!=null && rrr2.size()>0){
		// if(rrr2.get(0).getRemainCash()!=null){
		// rr.setEndAmount(rrr2.get(0).getRemainCash().toString());
		// }else{
		// rr.setEndAmount("0");
		// }
		// }else{
		//// // 如果大于该日期的 不存在，就取小于该日期的第一条
		//// List<RechargeRecoard> rrrr =
		// rechargeRecoardService.selectRechargeRecoardByUserPhone(searchEndAmount1);
		//// if(rrrr!=null && rrrr.size()>0){
		//// if(rrrr.get(0).getRemainCash()!=null){
		//// rr.setEndAmount(rrrr.get(0).getRemainCash().toString());
		//// }else{
		// rr.setEndAmount("0");
		//// }
		//// }
		// }
		// rrListReturn.add(rr);
		// }
		// Result.ok(rrListReturn, InfoCode.SUCCESS, response);

		Result.ok(rrList, InfoCode.SUCCESS, response);
		return null;
	}

	@RequestMapping(value = "/updatePaycashStatus", method = RequestMethod.POST)
	public @ResponseBody String updatePaycashStatus(@RequestParam("id") Integer id, // 用户账户
													@RequestParam("paycashStatus") Integer paycashStatus, // 充值金额Id
													HttpServletRequest request, HttpServletResponse response) {
		logger.info("配载费相关导出---收款---backRechargeController/updatePaycashStatus");
		try {
			RechargeRecoard rr = new RechargeRecoard();
			rr.setId(id);
			rr.setPaycashStatus(paycashStatus + "");

			int update = rechargeRecoardService.updateRechargeRecoard(rr);
			if (update > 0) {
				Result.ok(null, InfoCode.SUCCESS, response);
			} else {
				Result.ok(null, InfoCode.FAILURE, response);
				return null;
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			Result.ok(null, InfoCode.FAILURE, response);
		}
		return null;
	}
	public static void main(String[] args) {
		System.out.println(new Date().toLocaleString());
	}
}